<template>
  <div class="collections-container">
    <div class="header">
      <h1>🎨 我的藏品</h1>
      <el-button @click="loadMyNFTs" :loading="loading" type="primary">
        刷新
      </el-button>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <div v-else-if="nfts.length === 0" class="empty-state">
      <el-empty description="你还没有任何 NFT">
        <el-button type="primary" @click="$router.push('/mint')">
          铸造 NFT
        </el-button>
      </el-empty>
    </div>

    <div v-else class="nft-grid">
      <el-card 
        v-for="nft in nfts" 
        :key="nft.tokenId" 
        class="nft-card"
        shadow="hover"
      >
        <div class="nft-image-container">
          <img :src="getNFTImage(nft)" alt="NFT" class="nft-image" />
          <el-tag 
            v-if="nft.isListed" 
            type="success" 
            class="listed-tag"
          >
            已上架
          </el-tag>
        </div>
        
        <div class="nft-info">
          <h3>{{ getNFTName(nft) }}</h3>
          <p class="nft-description">{{ getNFTDescription(nft) }}</p>
          
          <el-divider />
          
          <div class="nft-details">
            <div class="detail-item">
              <span class="label">Token ID:</span>
              <span class="value">#{nft.tokenId}</span>
            </div>
            <div v-if="nft.isListed" class="detail-item">
              <span class="label">价格:</span>
              <span class="value price">{{ nft.price }} ETH</span>
            </div>
          </div>

          <div class="action-buttons">
            <template v-if="!nft.isListed">
              <el-button 
                type="primary" 
                @click="showListDialog(nft)" 
                style="flex: 1"
              >
                上架出售
              </el-button>
              <el-button 
                type="danger" 
                @click="handleBurn(nft)" 
                :loading="burning === nft.tokenId"
              >
                销毁
              </el-button>
            </template>
            <template v-else>
              <el-button 
                type="warning" 
                @click="showUpdatePriceDialog(nft)" 
                style="flex: 1"
              >
                修改价格
              </el-button>
              <el-button 
                type="info" 
                @click="handleUnlist(nft)" 
                :loading="unlisting === nft.tokenId"
              >
                下架
              </el-button>
            </template>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 上架对话框 -->
    <el-dialog v-model="listDialogVisible" title="上架 NFT" width="400px">
      <el-form :model="listForm">
        <el-form-item label="价格 (ETH)">
          <el-input-number 
            v-model="listForm.price" 
            :min="0.001" 
            :step="0.01" 
            :precision="3"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="listDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleList" 
          :loading="listing"
        >
          确认上架
        </el-button>
      </template>
    </el-dialog>

    <!-- 修改价格对话框 -->
    <el-dialog v-model="updatePriceDialogVisible" title="修改价格" width="400px">
      <el-form :model="updatePriceForm">
        <el-form-item label="新价格 (ETH)">
          <el-input-number 
            v-model="updatePriceForm.price" 
            :min="0.001" 
            :step="0.01" 
            :precision="3"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="updatePriceDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleUpdatePrice" 
          :loading="updatingPrice"
        >
          确认修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import web3Service from '../services/web3Service';

export default {
  name: 'MyCollections',
  setup() {
    const nfts = ref([]);
    const loading = ref(false);
    const listing = ref(false);
    const unlisting = ref(null);
    const burning = ref(null);
    const updatingPrice = ref(false);

    const listDialogVisible = ref(false);
    const updatePriceDialogVisible = ref(false);
    const listForm = ref({ tokenId: null, price: 0.01 });
    const updatePriceForm = ref({ tokenId: null, price: 0.01 });

    const getNFTImage = (nft) => {
      try {
        const metadata = parseTokenURI(nft.tokenURI);
        return metadata?.image || 'https://via.placeholder.com/300?text=NFT';
      } catch {
        return 'https://via.placeholder.com/300?text=NFT';
      }
    };

    const getNFTName = (nft) => {
      try {
        const metadata = parseTokenURI(nft.tokenURI);
        return metadata?.name || `NFT #${nft.tokenId}`;
      } catch {
        return `NFT #${nft.tokenId}`;
      }
    };

    const getNFTDescription = (nft) => {
      try {
        const metadata = parseTokenURI(nft.tokenURI);
        return metadata?.description || '暂无描述';
      } catch {
        return '暂无描述';
      }
    };

    const parseTokenURI = (tokenURI) => {
      if (tokenURI.startsWith('data:application/json;base64,')) {
        const base64Data = tokenURI.replace('data:application/json;base64,', '');
        return JSON.parse(atob(base64Data));
      }
      return null;
    };

    const loadMyNFTs = async () => {
      if (!web3Service.getAccount()) {
        ElMessage.warning('请先连接钱包');
        return;
      }

      try {
        loading.value = true;
        nfts.value = await web3Service.getMyNFTs();
      } catch (error) {
        ElMessage.error(error.message || '加载失败');
      } finally {
        loading.value = false;
      }
    };

    const showListDialog = (nft) => {
      listForm.value = { tokenId: nft.tokenId, price: 0.01 };
      listDialogVisible.value = true;
    };

    const showUpdatePriceDialog = (nft) => {
      updatePriceForm.value = { 
        tokenId: nft.tokenId, 
        price: parseFloat(nft.price) || 0.01 
      };
      updatePriceDialogVisible.value = true;
    };

    const handleList = async () => {
      try {
        listing.value = true;
        await web3Service.listNFT(listForm.value.tokenId, listForm.value.price);
        ElMessage.success('上架成功!');
        listDialogVisible.value = false;
        await loadMyNFTs();
      } catch (error) {
        ElMessage.error(error.message || '上架失败');
      } finally {
        listing.value = false;
      }
    };

    const handleUnlist = async (nft) => {
      try {
        await ElMessageBox.confirm('确定要下架这个 NFT 吗？', '确认下架', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        });

        unlisting.value = nft.tokenId;
        await web3Service.unlistNFT(nft.tokenId);
        ElMessage.success('下架成功!');
        await loadMyNFTs();
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(error.message || '下架失败');
        }
      } finally {
        unlisting.value = null;
      }
    };

    const handleUpdatePrice = async () => {
      try {
        updatingPrice.value = true;
        await web3Service.updateListingPrice(
          updatePriceForm.value.tokenId, 
          updatePriceForm.value.price
        );
        ElMessage.success('价格修改成功!');
        updatePriceDialogVisible.value = false;
        await loadMyNFTs();
      } catch (error) {
        ElMessage.error(error.message || '修改失败');
      } finally {
        updatingPrice.value = false;
      }
    };

    const handleBurn = async (nft) => {
      try {
        await ElMessageBox.confirm(
          '销毁后无法恢复，确定要销毁这个 NFT 吗？',
          '确认销毁',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'error'
          }
        );

        burning.value = nft.tokenId;
        await web3Service.burnNFT(nft.tokenId);
        ElMessage.success('销毁成功!');
        await loadMyNFTs();
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(error.message || '销毁失败');
        }
      } finally {
        burning.value = null;
      }
    };

    onMounted(() => {
      if (web3Service.getAccount()) {
        loadMyNFTs();
      }
    });

    return {
      nfts,
      loading,
      listing,
      unlisting,
      burning,
      updatingPrice,
      listDialogVisible,
      updatePriceDialogVisible,
      listForm,
      updatePriceForm,
      getNFTImage,
      getNFTName,
      getNFTDescription,
      loadMyNFTs,
      showListDialog,
      showUpdatePriceDialog,
      handleList,
      handleUnlist,
      handleUpdatePrice,
      handleBurn
    };
  }
};
</script>

<style scoped>
.collections-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 2rem;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.header h1 {
  margin: 0;
  color: #303133;
}

.loading-container {
  padding: 2rem;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.nft-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 2rem;
}

.nft-card {
  transition: transform 0.3s;
}

.nft-card:hover {
  transform: translateY(-5px);
}

.nft-image-container {
  position: relative;
  width: 100%;
  height: 300px;
  overflow: hidden;
  border-radius: 8px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nft-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.listed-tag {
  position: absolute;
  top: 10px;
  right: 10px;
}

.nft-info {
  padding: 1rem 0;
}

.nft-info h3 {
  margin: 0 0 0.5rem 0;
  color: #303133;
  font-size: 1.2rem;
}

.nft-description {
  color: #606266;
  font-size: 0.9rem;
  margin: 0;
  line-height: 1.5;
  max-height: 3em;
  overflow: hidden;
  text-overflow: ellipsis;
}

.nft-details {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-item .label {
  color: #909399;
  font-size: 0.9rem;
}

.detail-item .value {
  color: #303133;
  font-weight: 500;
}

.detail-item .price {
  color: #67c23a;
  font-size: 1.2rem;
  font-weight: bold;
}

.action-buttons {
  display: flex;
  gap: 0.5rem;
}
</style>

